package thread_test;

public class Stack {
    private Object[] stack;
    private int top;
    private int len;

    public Stack(int len) {
        this.stack = new Object[len];
        this.top = 0;
        this.len = len;
    }
    //入栈
    public synchronized void Push(Object o) {
        if(top>=len){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.stack[top++] = o;
        this.notifyAll();
    }
    //出栈
       //synchronized  同步，使用notify必须使用synchronized
    public synchronized Object Pop(){
        if(top <= 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notifyAll();
        return stack[--top];
    }
}
